// pages/install/lock/lock.js
const plugin = requirePlugin("myPlugin");
import {
	request
} from '../../../utils/api.js';
import {
	msg
} from '../../../utils/util.js'

const app = getApp();
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		locklist: [],
		alert: false,
		index: -1,
		admin_id: null,
		company: [],
		clist: [],
		item:null
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	close() {
		this.setData({
			alert: false
		})
	},
	onLoad: function(options) {

		this.setData({
			locklist: JSON.parse(decodeURIComponent(options.locklist)),
		})
		this.getcompany_list();

	},
	bindPickerChange(e) {
		this.setData({
			index: e.detail.value
		})
		const i = e.detail.value;
		this.setData({
			admin_id: this.data.clist[i].admin_user_id
		})
	},
	getcompany_list() {
		request({
			url: "/api/wxapi/company_list",
			header: {
				token: wx.getStorageSync('token')
			}
		}).then(res => {
			this.setData({
				company: res.data.list.map(item => {
					return item.company
				}),
				clist: res.data.list
			})

		})
	},
	bind(e) {
		this.setData({
			alert: true
		})
		const item = this.data.locklist[e.currentTarget.dataset.index];
		this.setData({
			item
		})
	},
	bindlock(callback) {
		const item = this.data.item;
		//console.log(item);
		if (!item.isSettingMode) {
			wx.showModal({
				content: "智能锁不可添加"
			})
			return;
		}
		//console.log("正在初始化蓝牙智能锁" + item.lockMac);
		wx.showLoading({
			title: '绑定中',
		})
		plugin.initLock(item, res => {
			console.log('3333333333' + res.errorCode);
			if (res.errorCode === 0) {
				wx.hideLoading()
				console.log(res.lockData);
				callback(res.lockData)
			} else {
				wx.showModal({
					content: "绑定失败！"
				})
				return;
			}
		})

	},
	formSubmit(e) {
		
		if (!this.data.admin_id) {
			wx.showModal({
				content: '请选择单位！'
			})
			return;
		}
		if (!e.detail.value.ordername) {
			wx.showModal({
				content: '请输入订单名称！'
			})
			return;
		}
		if (!e.detail.value.lockname) {
			wx.showModal({
				content: '请输入锁名称！'
			})
			return;
		}
		if (!e.detail.value.lockaddress) {
			wx.showModal({
				content: '请输入安装位置！'
			})
			return;
		}
        this.bindlock((lockData)=>{
			request({
				url: '/api/wxapi/lock_init',
				data: {
					...e.detail.value,
					admin_id: this.data.admin_id,
					lockdata:lockData
				},
				header: {
					token: wx.getStorageSync('token')
				}
			}).then(res => {
				if(res){
					wx.showModal({
						content: res.data.msg
					})
					this.setData({
						alert: false
					})
				}else{
					wx.showModal({
						content: '服务器错误！'
					})
				}
			})
		});
		
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function() {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function() {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function() {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function() {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function() {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function() {

	}
})
